package com.kurumi.autoprint.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class YinlianPayUtilTest {
	//测试
	//static String appId = "10037ca764636bbc01647d1ef4e10009";
	//static String appKey = "389d830dcc0c46a58b0ea1962041e497";
	//正式
	static String appId = "8a81c1be6d4ad929016ec4b548d60834";
    static String appKey = "309bb4171a7b49d68f95a93a35a9bc91";
	static String authorization;

	public static String send(String url, String entity) throws Exception {
		authorization = getOpenBodySig(appId, appKey, entity);
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		httpPost.addHeader("Authorization", authorization);
		StringEntity se = new StringEntity(entity, "UTF-8");
		se.setContentType("application/json");
		httpPost.setEntity(se);
		CloseableHttpResponse response = httpClient.execute(httpPost);
		HttpEntity entity1 = response.getEntity();
		String resStr = null;
		if (entity1 != null) {
			resStr = EntityUtils.toString(entity1, "UTF-8");
		}
		httpClient.close();
		response.close();
		return resStr;
	}
	
	
	public static String send(String url,String authorization, String entity) throws Exception {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		httpPost.addHeader("Authorization", authorization);
		StringEntity se = new StringEntity(entity, "UTF-8");
		se.setContentType("application/json");
		httpPost.setEntity(se);
		CloseableHttpResponse response = httpClient.execute(httpPost);
		HttpEntity entity1 = response.getEntity();
		String resStr = null;
		if (entity1 != null) {
			resStr = EntityUtils.toString(entity1, "UTF-8");
		}
		httpClient.close();
		response.close();
		return resStr;
	}

	public static String getOpenBodySig(String appId, String appKey, String body) throws Exception {
		String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		String nonce = UUID.randomUUID().toString().replace("-", "");
		// String timestamp ="20191217105731";
		// String nonce
		// ="56548739295648788745791425133429327818843849435659236726618617265657711657952724271549568584292395186895354815832918166775279458";
		byte[] data = body.getBytes("UTF-8");
		System.out.println("data:\n" + body);
		InputStream is = new ByteArrayInputStream(data);
		String bodyDigest = testSHA256(is);
		System.out.println("bodyDigest:\n" + bodyDigest);
		String str1_C = appId + timestamp + nonce + bodyDigest;

		System.out.println("str1_C:\n" + str1_C);

//        System.out.println("appKey_D:\n" + appKey);

		byte[] localSignature = hmacSHA256(str1_C.getBytes(), appKey.getBytes());
		// System.out.println(Arrays.toString(localSignature));
		String localSignatureStr = Base64.encodeBase64String(localSignature);
		System.out.println(
				"Authorization:\n" + "OPEN-BODY-SIG AppId=" + "\"" + appId + "\"" + ", Timestamp=" + "\"" + timestamp
						+ "\"" + ", Nonce=" + "\"" + nonce + "\"" + ", Signature=" + "\"" + localSignatureStr + "\"");
		return ("OPEN-BODY-SIG AppId=" + "\"" + appId + "\"" + ", Timestamp=" + "\"" + timestamp + "\"" + ", Nonce="
				+ "\"" + nonce + "\"" + ", Signature=" + "\"" + localSignatureStr + "\"");
	}

	private static String testSHA256(InputStream is) {
		try {
//            System.out.println(is.hashCode());
			return DigestUtils.sha256Hex(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static byte[] hmacSHA256(byte[] data, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException {
		String algorithm = "HmacSHA256";
		Mac mac = Mac.getInstance(algorithm);
		mac.init(new SecretKeySpec(key, algorithm));
		return mac.doFinal(data);
	}

	public static void payV2() throws Exception {
		String body = "{\"merchantCode\":\"103290070111407\",\"terminalCode\":\"12340045\",\"transactionAmount\":\"1\",\"transactionCurrencyCode\":\"156\",\"merchantOrderId\":\"345223421221222467\",\"notifyUrl\":\"https://www.baidu.com/\",\"payMode\":\"MANUAL\",\"payCode\":\"134782154660933044\"}}";
		// V2
		String url = "http://58.247.0.18:29015/v2/poslink/transaction/pay";
		System.out.println(send(url, body));
	}

	// 生成二维码
	public static void payv1() throws Exception {

		Map<String, Object> map = new HashMap<>();
		map.put("msgId", StringUtil.getId());
		map.put("requestTimestamp", DateUtil.dateFormat("yyyy-MM-dd HH:mm:ss", new Date()));
		map.put("mid", "898370680620456");
		map.put("tid", "86221950");
		map.put("instMid", "898370680620456");
		
		map.put("billNo", generateBillNo(null));
		
		
		map.put("billDate", DateUtil.dateFormat("yyyy-MM-dd", new Date()));
		map.put("totalAmount", "1");
		//测试
		//String url = "http://58.247.0.18:29015/v1/netpay/bills/get-qrcode";
		//生产
		String url = "https://api-mop.chinaums.com/v1/netpay/bills/get-qrcode";
		String result = send(url, JsonUtil.objectToJson(map));
		System.out.println(JsonUtil.jsonToPojo(result, Map.class));
	}

	// 刷新二维码
	public static void payv2() throws Exception {
		
		//{"qrCodeId":"10171912252811007110891097","errMsg":"查询二维码成功","mid":"898340149000035","msgId":"9f35ec48ec3d461aa7a7f2e62dc1a78a","billDate":"2019-12-25","tid":"38557688","instMid":"QRPAYDEFAULT","responseTimestamp":"2019-12-25 11:10:07","errCode":"SUCCESS","billNo":"101711112","billQRCode":"https://qr-test3.chinaums.com/bills/qrCode.do?id=10171912252811007110891097"}


		Map<String, Object> map = new HashMap<>();
		map.put("requestTimestamp", DateUtil.dateFormat("yyyy-MM-dd HH:mm:ss", new Date()));
		map.put("mid", "898340149000035");
		map.put("tid", "38557688");
		map.put("billDate", DateUtil.dateFormat("yyyy-MM-dd", new Date()));
		map.put("qrCodeId", "10171912253134501111290815");
		map.put("msgId","d59374cd95154e5186784b1dcf65fa59");
		
		

		String url = "http://58.247.0.18:29015/v1/netpay/bills/update-qrcode";
		String result = send(url, JsonUtil.objectToJson(map));
		System.out.println(JsonUtil.jsonToPojo(result, Map.class));
	}
	
	
	/**
	 * 生成订单号
	 * @return
	 */
	public static String generateBillNo(String msgSrcId) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddmmHHssSSS");
		StringBuilder builder = new StringBuilder();
		if(StringUtils.isNotBlank(msgSrcId)) {
			builder.append(msgSrcId);
		}else {
			builder.append("6668");
		}
		
		String timeStamp = sdf.format(new Date());
		builder.append(timeStamp).append(StringUtil.rand());
		return builder.toString();
		
	}
	
	
	// 刷新二维码
	public static void testPayResult() throws Exception {


		Map<String, Object> map = new HashMap<>();
		map.put("requestTimestamp", DateUtil.dateFormat("yyyy-MM-dd HH:mm:ss", new Date()));
		map.put("mid", "898370680620456");
		map.put("tid", "86221950");
		map.put("instMid", "APPDEFAULT");
		map.put("billDate", DateUtil.dateFormat("yyyy-MM-dd", new Date()));
		map.put("billNo", "6668201912301615229687777636");
		
		

		String url = "https://api-mop.chinaums.com/v1/netpay/bills/query";
		String result = send(url, JsonUtil.objectToJson(map));
		System.out.println(JsonUtil.jsonToPojo(result, Map.class));
	}
	
	
	//{"qrCodeId":"10171912253134501111290815","errMsg":"查询二维码成功","mid":"898340149000035","msgId":"d59374cd95154e5186784b1dcf65fa59","billDate":"2019-12-25","tid":"38557688","instMid":"QRPAYDEFAULT","responseTimestamp":"2019-12-25 11:45:01","errCode":"SUCCESS","billNo":"1017111898898990999","billQRCode":"https://qr-test3.chinaums.com/bills/qrCode.do?id=10171912253134501111290815"}

	
	// 关闭二维码
	public static void payv3() throws Exception {
			
			//{"qrCodeId":"10171912252811007110891097","errMsg":"查询二维码成功","mid":"898340149000035","msgId":"9f35ec48ec3d461aa7a7f2e62dc1a78a","billDate":"2019-12-25","tid":"38557688","instMid":"QRPAYDEFAULT","responseTimestamp":"2019-12-25 11:10:07","errCode":"SUCCESS","billNo":"101711112","billQRCode":"https://qr-test3.chinaums.com/bills/qrCode.do?id=10171912252811007110891097"}
		//{"qrCodeId":"10171912257143013110482980","errMsg":"查询二维码成功","mid":"898340149000035","msgId":"8ba8fd91d76d4a939ddc955f84ecd861","billDate":"2019-12-25","tid":"38557688","instMid":"QRPAYDEFAULT","responseTimestamp":"2019-12-25 11:30:13","errCode":"SUCCESS","billNo":"10171118988989","billQRCode":"https://qr-test3.chinaums.com/bills/qrCode.do?id=10171912257143013110482980"}
//{"qrCodeId":"10171912252083436112217543","errMsg":"查询二维码成功","mid":"898340149000035","msgId":"9b6b8e9609ea4cc3b7dd991c028d49fc","billDate":"2019-12-25","tid":"38557688","instMid":"QRPAYDEFAULT","responseTimestamp":"2019-12-25 11:34:36","errCode":"SUCCESS","billNo":"1017111898898990","billQRCode":"https://qr-test3.chinaums.com/bills/qrCode.do?id=10171912252083436112217543"}


			Map<String, Object> map = new HashMap<>();
			map.put("requestTimestamp", DateUtil.dateFormat("yyyy-MM-dd HH:mm:ss", new Date()));
			map.put("mid", "898340149000035");
			map.put("tid", "38557688");
			map.put("qrCodeId", "10171912257143013110482980");
			
			

			String url = "http://58.247.0.18:29015/v1/netpay/bills/close-qrcode";
			System.out.println(send(url, JsonUtil.objectToJson(map)));
		}

	public static void main(String[] args) throws Exception {
		 payv1();
		
		//System.out.println(generateBillNo());
	}
}
